package com.agent.rag.controller;

import com.agent.commons.Result.Result;
import com.agent.commons.enums.FileType;
import com.agent.commons.exception.BaseException;
import com.agent.commons.other.ThreadLocal;
import com.agent.feign.entity.SearchEntity;
import com.agent.rag.param.RagParam;
import com.agent.rag.service.RagService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.agent.commons.errorcode.ServiceErrorCodeConstants.*;

import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/rag")
@Slf4j
public class RagController {
    @Resource
    private RagService ragService;

    /**
     * 进行文件Rag搭建本地知识库操作操作
     * @return
     */
    @PostMapping("/rag/{type}")
    public Result<Boolean> rag(@PathVariable String type, @RequestPart("file") MultipartFile file) throws IOException {
        //设置压缩文件大小限制
        ZipSecureFile.setMinInflateRatio(0.001);
        //验证文件类型
        //1.获取文件名称
        String originalFilename = file.getOriginalFilename();
        //2.获取文件后缀
        if (originalFilename == null) {
            throw new BaseException(FILE_NOT_TRANSFER);
        }
        String end=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        //匹配文件类型进行对应处理
        ragService.actionFile(end,file);
        return Result.success(true);
    }

    /**
     * 检索知识库获取相似知识
     */
    @GetMapping("/search")
    public List<SearchEntity> search(@RequestParam String text){
        String userId=ThreadLocal.getUserId();
        log.info("用户ID:{}",userId);
        List<SearchEntity> knowledge = ragService.getKnowledge(text, userId);
        System.out.println(knowledge);
        return knowledge;
    }

}
